//
//  ZLTextView.swift
//  ZLKit_SwiftDemo_Example
//
//  Created by itzhaolei on 2022/1/17.
//  Copyright © 2022 CocoaPods. All rights reserved.
//


open class ZLTextView: UITextView, UITextViewDelegate {
    
    public var maxLength: Int = 0
    
    /// 第一响应者事件监听
    public var firstResponderHandler: Params_one_void<Bool> = nil
    
    public var placeholder: String = "" {
        didSet {
            placeholderLabel.text = placeholder
        }
    }
    
    /// 输入改变
    public var editingChangedHandler: Params_one_void<String?> = nil
    
    /// 点击完成
    public var clickDone: Params_one_void<String> = nil
    
    public var attributed_placeholder: NSAttributedString = .init() {
        didSet {
            placeholderLabel.attributedText = attributed_placeholder
            placeholderLabel.numberOfLines = 0
        }
    }
    
    public var placeholder_textColor: UIColor = .hex_CCCCCC {
        didSet {
            placeholderLabel.textColor = placeholder_textColor
        }
    }
    
    public override var font: UIFont? {
        didSet {
            placeholderLabel.font = font
        }
    }
    
    public override var textAlignment: NSTextAlignment {
        didSet {
            placeholderLabel.textAlignment = textAlignment
        }
    }
    
    public var done_title: String = "" {
        didSet {
            doneItem.text = done_title
        }
    }
    
    public override var text: String! {
        didSet {
            placeholderLabel.isHidden = text != ""
            if text.count > maxLength {
                self.text = text.ns.substring(to: maxLength)
                editingChangedHandler?(self.text)
            }
        }
    }
    
    /// 占位文字
    public lazy var placeholderLabel: UILabel = {
        let view = UILabel()
        view.text = "请输入内容"
        view.textColor = .hex_CCCCCC
        view.font = .pingFangSC(ofSize: 17, weight: .medium)
        view.numberOfLines = 0
        return view
    }()
    
    /// 工具条
    lazy var _inputAccessoryView: UIView = {
        let view = UIView(frame: .init(x: 0, y: 0, width: UIScreen.main.bounds.width, height: 40))
        view.backgroundColor = .hex_FFFFFF
        return view
    }()
    
    /// 完成
    public lazy var doneItem: UILabel = {
        let view = UILabel()
        view.text = "完成"
        view.font = .pingFangSC(ofSize: 15, weight: .medium)
        view.textColor = .hex_333333
        view.textAlignment = .center
        view.action.tap = {[weak self] _ in
            self?.doneItemAction()
        }
        return view
    }()
    
    deinit {
        removeNotification(name: UITextView.textDidChangeNotification, observer: self)
    }
    
    public override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: .zero, textContainer: nil)
        autocapitalizationType = .none
        autocorrectionType = .no
        backgroundColor = .clear
        font = .pingFangSC(ofSize: 17, weight: .medium)
        textColor = .hex_333333
        delegate = self
        self.textContainer.lineFragmentPadding = 0
        textContainerInset = .zero
        inputAccessoryView = _inputAccessoryView
        addSubviews()
        addConstraints()
        addNotification(name: UITextView.textDidChangeNotification, observer: self, selector: #selector(editingChangedAction(_:)))
    }
        
    required public init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    private func addSubviews() {
        addSubview(placeholderLabel)
        _inputAccessoryView.addSubview(doneItem)
    }
    
    private func addConstraints() {
        placeholderLabel.snp.makeConstraints {
            $0.edges.width.equalToSuperview()
        }
        doneItem.snp.makeConstraints {
            $0.centerY.equalToSuperview()
            $0.trailing.equalToSuperview().inset(15)
        }
    }
    
    @objc private func doneItemAction() {
        endEditing(false)
        let text = text ?? ""
        clickDone?(text)
    }
    
    @objc func editingChangedAction(_ notifi: Notification) {
        let textView: UITextView = notifi.object as? UITextView ?? .init()
        guard textView == self else { return }
        guard let _: UITextRange = textView.markedTextRange else {
            if ((textView.text ?? "") as NSString).length >= maxLength && maxLength > 0 {
                textView.text = (textView.text! as NSString).substring(to: maxLength)
                editingChangedHandler?(textView.text)
            }else {
                editingChangedHandler?(textView.text)
            }
            placeholderLabel.isHidden = text != ""
            return
        }
        placeholderLabel.isHidden = text != ""
    }
    
    @discardableResult
    open override func becomeFirstResponder() -> Bool {
        firstResponderHandler?(true)
        return super.becomeFirstResponder()
    }
    
    @discardableResult
    open override func resignFirstResponder() -> Bool {
        firstResponderHandler?(false)
        return super.resignFirstResponder()
    }
    
}
